#include <iostream>
#include <mysql/mysql.h>

using namespace std;

const string userName = "zhiang";
const string password = "12345678.";
const string host = "127.0.0.1";
const string database = "conn";
const int port = 1314;

int main()
{
    MYSQL* my;
    my = mysql_init(nullptr);
    if(my == nullptr)
    {
        cerr << "mysql_init failed" << endl;
        return 1;
    }
    my = mysql_real_connect(my, host.c_str(), userName.c_str(), password.c_str(), database.c_str(), port, nullptr, 0);
    if(my == nullptr)
    {
        cerr << "mysql_real_connect failed" << endl;
        mysql_close(my);
        return 2;
    }
    cout << "Connected to MySQL server successfully!" << endl;
    // const string sql = "create table users (                \\
    //                         id bigint primary key auto_increment,\\
    //                         name varchar(20) not null,        \\
    //                         age int not null,                \\
    //                         phone varchar(20) unique not null      \\
    //                     );";
    // const string sql = "insert into users (name, age, phone) values ('jimi', 29, '341115');";
    string sql = "select * from users";
    cout << "mysql> ";
    getline(cin, sql);
    if(mysql_query(my, sql.c_str()))
    {
        cerr << "mysql_query failed: " << mysql_error(my) << endl;
        mysql_close(my);
        return 3;
    }
    cout << "sql successfully!" << endl;

    MYSQL_RES* res = mysql_store_result(my);
    if(nullptr == res)
    {
        cerr << "mysql result error" << endl;
        return 4;
    }
    int rows = mysql_num_rows(res);
    int fields = mysql_num_fields(res);
    cout << "行：" << rows << endl;
    cout << "列：" << fields << endl;

    MYSQL_FIELD* fields_array = mysql_fetch_fields(res);
    for(int i = 0; i < fields; i++)
    {
        cout << fields_array[i].name << ' ';
    }
    cout << endl; 
    
    for(int i = 0; i < rows; i++)
    {
        MYSQL_ROW row = mysql_fetch_row(res);
        for(int j = 0; j < fields; j++)
        {
            cout << row[j] << ' ';
        }
        cout << endl;
    }

    mysql_free_result(res);
    mysql_close(my);
    my = nullptr;
    return 0;
}